#!/bin/sh
###############################################################################
##  Author    : xuezhoyi
##  Name      : edw_batch_start.sh
##  Functions : 
##  Purpose   : 
##  Revisions or Comments
##  VER        DATE        AUTHOR           DESCRIPTION
##---------  ----------  ---------------  ------------------------------------ 
##  1.0      2017-05-22  xuezhouyi        1. CREATED THIS SHELL.
###############################################################################

. ${0%`basename ${0}`}edw_parm.sh
. ${0%`basename ${0}`}edw_func.sh

function USAGE(){
    echo -e "\nHow to use this shell script!"
    echo -e '\n${V_SHELL_HOME}/edw_batch_start.sh 20170101'
}

# Check variable
if [[ -z ${1} ]];then
    USAGE
    exit 1
fi

# Define basic parm
V_SCRIPT_NAME=$(basename ${0} | cut -d'.' -f1)
V_OUT_LOGS="${V_SHELL_LOGS}/${V_SCRIPT_NAME}_${V_TIME_STAMP}_$$.log"

# Define the output flow
exec 4>&1               # screen output
exec 3>>${V_OUT_LOGS}   # script output
exec 2>&3               # error output
exec 1>&3               # standard output
echo -e "[Begin: $(date +%F) $(date +%T)]"

# Get parm
V_DATA_DATE=${1}
echo -e "\nToday batch date is ${V_DATA_DATE}."

# Update start time
V_QUERY="UPDATE ETL.EDW_BATCH_CONTROL SET START_TIME = NOW() WHERE DATA_DATE = '${V_DATA_DATE}';"
${V_RUN_MYSQL} -q "${V_QUERY}"
if [[ $? -eq 0 ]];then
    echo -e "\nSuccess to start batch...\n"
else
    echo -e "\nCan not update START_TIME."
    echo -e "\n${V_QUERY}"
    exit 1
fi

# Get the group list from EDW_ORG_INFO
V_QUERY="DELETE FROM ETL.EDW_JOB_STATUS WHERE DATA_DATE = '${V_DATA_DATE}';"
${V_RUN_MYSQL} -q "${V_QUERY}"
V_QUERY="SELECT ORG_NO FROM ETL.EDW_ORG_INFO WHERE IF_VALID <> 'N';"
V_GROUP_LIST=$(${V_RUN_MYSQL} -q "${V_QUERY}")
for GROUP in ${V_GROUP_LIST};do
    if [[ ${GROUP} == 'ALL_ORG' ]];then
        # Initinal the table EDW_JOB_STATUS
        V_QUERY="INSERT INTO ETL.EDW_JOB_STATUS(DATA_DATE,ORG_TYPE,JOB_GROUP,SEQ_NO,PROC_NAME) SELECT '${V_DATA_DATE}','ALL_ORG',JOB_GROUP,SEQ_NO,PROC_NAME FROM ETL.EDW_JOB_CONTROL WHERE JOB_TYPE = 'ALL_ORG' AND IF_VALID = 'Y';"
        ${V_RUN_MYSQL} -q "${V_QUERY}"
    else
        # Initinal the table EDW_JOB_STATUS
        V_QUERY="INSERT INTO ETL.EDW_JOB_STATUS(DATA_DATE,ORG_TYPE,JOB_GROUP,SEQ_NO,PROC_NAME) SELECT '${V_DATA_DATE}','${GROUP}',JOB_GROUP,SEQ_NO,PROC_NAME FROM ETL.EDW_JOB_CONTROL WHERE JOB_TYPE = 'FIN_ORG' AND IF_VALID = 'Y';"
        ${V_RUN_MYSQL} -q "${V_QUERY}"
    fi
    
    echo -e "Success to initinal ${GROUP}..."
done
if [[ $? -eq 0 ]];then
    echo -e "\nSuccess to initinal table ETL.EDW_JOB_STATUS."
else
    echo -e "\nEROR:Fail to initinal table ETL.EDW_JOB_STATUS."
    exit 1
fi

echo -e "\n[End: $(date +%F) $(date +%T)]"
echo 0 >&4
exit 0
